<?php
namespace app\beautiful\logic;
use app\beautiful\model\mall\FreightTemplateModel;
use app\beautiful\model\mall\FreightTemplatePieceModel;

class FreightLogic{
    protected $shopId;
    public function __construct($shopId)
    {
        $this->shopId=$shopId;
    }

    public function getFreightPrice($province,$num)
    {
        $price=0;

        if(empty($province)) return $price;

        if(null === $freight_template = FreightTemplateModel::where('shop_id',$this->shopId)->find()){
            return $price;
        }

        if(in_array($province,$freight_template->no_delivery_area)){
            return -1; //暂不发货
        }

        if($freight_template->freight_type==1) return $price;
        if($freight_template->valuation_type!=1) return $price;

        if(null === $freight_template_piece = FreightTemplatePieceModel::where('freight_template_id',$freight_template->freight_template_id)->find()){
            return $price;
        }

        if(!empty($freight_template_piece->piece_data) && is_array($freight_template_piece->piece_data)){
            $piece_data=$freight_template_piece->piece_data;
            foreach ($piece_data as $k =>$v){
                if(in_array($province,$v['designated_area'])){
                    $remain_num=$num - $v['base_piece_num'];
                    if($remain_num>0){
                        $price=round(($price*100+($v['base_piece_price'])*100)/100,2);
                        $price=round(($price*100+((ceil($remain_num/$v['add_piece_num']) * $v['add_piece_price']))*100)/100,2);
                    }else{
                        $price=$v['base_piece_price'];
                    }
                    return $price;
                }
            }
        }

        $remain_num=$num - $freight_template_piece->base_piece_num;
        if($remain_num>0){
            $price=round(($price*100+($freight_template_piece->base_piece_price)*100)/100,2);
            $price=round(($price*100+((ceil($remain_num/$freight_template_piece->add_piece_num) * $freight_template_piece->add_piece_price))*100)/100,2);
        }else{
            $price=$freight_template_piece->base_piece_price;
        }
        return $price;

    }
}
